package top.IT00544.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
 * 连接sqlite DB的工具
 * @author universe
 *
 */
public class SqliteDBTools {

	public static Connection conn = null;
	public static String dbName;

	public SqliteDBTools() {
		try {
			Class.forName("org.sqlite.JDBC");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取sqlite的conn
	 * 建立一个数据库名dbName的连接
	 *   新建条件：
	 *     1.conn关闭里
	 *     2.conn == null
	 *     3.dbName与当前conn不一致
	 *   否则，返回当前已经存在的conn
	 * @param dbName 形如  abc.db,c:/abc.db
	 * @return 数据库连接 conn
	 */
	public static Connection getConn(String dbName) {
		try {
			if(!dbName.equals(SqliteDBTools.dbName)||null == conn||conn.isClosed()) {
				System.out.println("创建sqlite链接");
				SqliteDBTools.dbName = dbName;
				//关闭当前链接
				releaseDB(null,null,conn);
				//获取新的链接
				conn = DriverManager.getConnection("jdbc:sqlite:"+dbName);
			}
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}
		return conn;
	}
	/**
	 * 释放DB资源
	 * @param resultSet
	 * @param statement
	 * @param connection
	 */
	public static void releaseDB(ResultSet resultSet, Statement statement,
			Connection connection) {
		System.out.println("关闭resultSet,Statement,connection");
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (connection != null) {
			try {
				//数据库连接池的 Connection 对象进行 close 时,
				//并不是真的进行关闭, 而是把该数据库连接归还到数据库连接池中. 
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
